<?php
namespace app\admin\controller;

use app\BaseController;
use app\admin\model\Admin;
use app\admin\validate\Admin as adminValidate;
use think\facade\Request;
use think\facade\Validate;
use verify\Verify;
use think\facade\Config;
class Login
{
    public function login(){
        return view('/login');
    }
    // 登录操作
    public function doLogin()
    {
        $userName = input("param.user_name");
        $password = input("param.password");
        $code = input("param.code");

        $result=(new \app\admin\validate\Admin())->goCheck();

        if($result!==true){
            return json(['code'=>0,'msg'=>$result]);
        }

        $verify = new Verify();
        if (!$verify->check($code)) {
            return json(['code'=>0,'msg'=>'验证码错误']);
        }

        $adminModel = new Admin();
        $hasUser = $adminModel->checkUser($userName);


        if(empty($hasUser)){
            return json(['code'=>0,'msg'=>'管理员不存在']);
        }
        if(md5($password .Config::get('app.salt') ) != $hasUser['password']){
            return json(['code'=>0,'msg'=>'密码错误']);
        }

        if(1 != $hasUser['status']){
            return json(['code'=>0,'msg'=>'该账号被禁用']);
        }

        $this->session = session('username', $hasUser['user_name']);
        $this->session;
        session('id', $hasUser['id']);
        session('head', $hasUser['head']);
        session('role', $hasUser['role_name']);  // 角色名
        session('role_id', $hasUser['role_id']);
        session('rule', $hasUser['rule']);


        // 更新管理员状态
        $param = [
            'login_nums'=>$hasUser['login_nums']+1,
            'last_login_ip'=>Request::ip(),
            'last_login_time' => date('Y-m-d H:i:s',time())
        ];

        $res = $adminModel->updateStatus($param, $hasUser['id']);
        if(1 != $res['code']){
            return json(['code'=>0,'msg'=>$res['msg']]);
        }
        return json(['code'=>1,'msg'=>'登录成功','data'=>url('admin/index/index')]);
    }
    //验证码
    public function checkVerify()
    {
        $verify = new Verify();
        $verify->imageH = 32;
        $verify->imageW = 100;
        $verify->codeSet = '0123456789';
        $verify->length = 4;
        $verify->useNoise = false;
        $verify->fontSize = 14;
        return $verify->entry();
    }


}
